package ElectricCraft.misc;

import java.util.Arrays;

/**
 * IntArray represents resizable array of ints.
 */
public final class IntArray {
    private int size;
    private int capacity;
    private int [] data;

    public IntArray() {
        free();
    }

    public void append(int value) {
        if (size + 1 >= capacity) {
            reserve(capacity + (capacity >> 1));
        }

        data[size] = value;
        ++size;
    }

    public int get(int index) {
        assert index < size;
        return data[index];
    }

    public void set(int index, int value) {
        assert index < size;
        data[index] = value;
    }

    public void resize(int size, int newValue) {
        if (size > capacity) {
            reserve(Math.max(size, capacity + (capacity >> 1)));
        }

        Arrays.fill(data, this.size, size, newValue);
        this.size = size;
    }

    public void growResize(int size, int newValue) {
        if (size <= this.size) {
            return ;
        }

        resize(size, newValue);
    }

    public void clear() {
        size = 0;
    }

    public void free() {
        size = 0;
        capacity = 32;
        data = new int[capacity];
    }

    public void reserve(int capacity) {
        if (capacity < this.capacity) {
            return ;
        }

        int [] newData = new int[capacity];
        System.arraycopy(data, 0, newData, 0, size);

        this.capacity = capacity;
        data = newData;
    }

    public int [] toArray() {
        int [] res = new int[size];
        System.arraycopy(data, 0, res, 0, size);
        return res;
    }

    public int indexOf(int group) {
        for (int k = 0; k < size; ++k) {
            if (data[k] == group) {
                return k;
            }
        }

        return -1;
    }
}
